import qs from "qs";
import axios from "axios";
import storage from "@/utils/storage";
import { responseSuccess, responseError } from "./config"

const config = require("../../config");

// 全局配置
// 创建 axios 实例
const service = axios.create({
  baseURL: config.api, // url = base url + request url
  timeout: 10000 // request timeout
});

service.interceptors.request.use(
  (config: Record<string, any>) => {
    // 这里的config包含每次请求的内容
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    config.headers["Accept"] = "application/json";
    // 添加参数
    const token = storage.get("TOKEN") || null;
    if (token) {
      // 如果token不为null，否则传token给后台
      config.headers["Token"] = token;
    }

    const data = qs.parse(config.data);
    for (const key in data) {
      if (!data[key]) delete data[key];
    }

    return config;
  },
  (error: Record<string, any>) => {
    console.warn(error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response: any) => {
   return response;
  },
  (error: any) => {
    return Promise.resolve(error);
  }
);

// 请求方式配置
const Http: Record<string, any> = {};

Http.post = function (url: string, data: Record<string, any>) {
  return service({
    method: "post",
    url,
    data
  })
    .then((Response: Record<string, any>) => {
      return responseSuccess(Response);
    })
    .catch((Response: Record<string, any>) => {
      return responseError(Response);
    });
};
Http.get = function (url: string, params: Record<string, any>) {
  // get
  return service({
    method: "get",
    url,
    params // get 请求时带的参数
  })
    .then((Response: any) => {
      return responseSuccess(Response);
    })
    .catch((Response: any) => {
      return responseError(Response);
    });
};

Http.put = function (url: string, data: Record<string, any>) {
  return service({
    method: "put",
    url,
    data
  })
    .then((Response: Record<string, any>) => {
      return responseSuccess(Response);
    })
    .catch((Response: Record<string, any>) => {
      return responseError(Response);
    });
};

Http.delete = function (url: string, params: Record<string, any>) {
  return service({
    method: "delete",
    url,
    params
  })
    .then((Response: Record<string, any>) => {
      return responseSuccess(Response);
    })
    .catch((Response: Record<string, any>) => {
      return responseError(Response);
    });
};

export default Http;
